import React, { useState, useRef, useEffect } from 'react';
import { Input, Button, Form, Radio, Checkbox, Rate, message, Typography, Card } from 'antd';
import { fetchSurveyById, submitSurveyAnswers } from '../services/survey';
import { getEmailFromToken } from '../utils/getemailfromtoken';
import { SearchOutlined, DownOutlined, UpOutlined, EnvironmentOutlined } from '@ant-design/icons';
import './WriteSurvey.css';

const { Title } = Typography;

const typeOrder = ['single', 'multiple', 'text', 'rating', 'location'];
const typeLabels = {
  single: '单选题',
  multiple: '多选题',
  text: '填空题',
  rating: '打分题',
  location: '定位题',
};

const getOptionLabelWithLetter = (option, index) => {
  const letter = String.fromCharCode(65 + index); // A, B, C...
  return `${letter}. ${option}`;
};

// 通过经纬度获取城市名的函数
const getCityName = async (lat, lng) => {
  try {
    // 使用高德地图逆地理编码API（免费版）
    const response = await fetch(
      `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${lng},${lat}&key=YOUR_AMAP_KEY&radius=1000&extensions=base`
      
      
    );
    console.log("response",response);
    
    if (!response.ok) {
      // 如果高德API不可用，使用OpenStreetMap的Nominatim服务
      const osmResponse = await fetch(
        `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&accept-language=zh-CN`
      );
      
      if (osmResponse.ok) {
        const osmData = await osmResponse.json();
        const city = osmData.address?.city || osmData.address?.town || osmData.address?.village || '未知城市';
        return city;
      }
      
      return '未知城市';
    }
    
    const data = await response.json();
    console.log("data",data);
    
    if (data.status === '1' && data.regeocode) {
      const city = data.regeocode.addressComponent?.city || '未知城市';
      return city;
    }
    
    return '未知城市';
  } catch (error) {
    console.error('获取城市名失败:', error);
    return '未知城市';
  }
};

const WritedSurveys = () => {
  const [surveyLink, setSurveyLink] = useState('');
  const [survey, setSurvey] = useState(null);
  const [form] = Form.useForm();
  const questionRefs = useRef([]);
  const [formValues, setFormValues] = useState({});
  const [activeNavigation, setActiveNavigation] = useState(false);
  const [locationInfo, setLocationInfo] = useState({}); // 存储每个定位题的位置信息

  useEffect(() => {
    const savedSurvey = localStorage.getItem('unsavedSurvey');
    const savedValues = localStorage.getItem('unsavedSurveyValues');
    if (savedSurvey) setSurvey(JSON.parse(savedSurvey));
    if (savedValues) {
      const parsed = JSON.parse(savedValues);
      form.setFieldsValue(parsed);
      setFormValues(parsed);
    }
  }, [form]);

  useEffect(() => {
    if (survey) {
      localStorage.setItem('unsavedSurvey', JSON.stringify(survey));
      localStorage.setItem('unsavedSurveyValues', JSON.stringify(formValues));
    }
  }, [survey, formValues]);

  const handleLoadSurvey = async () => {
    const match = surveyLink.match(/\/surveys\/([a-f0-9-]+)/i);
    if (!match) {
      message.error("链接格式无效，请输入包含问卷ID的链接");
      return;
    }
    const id = match[1];
    try {
      const surveyData = await fetchSurveyById(id);
      if (surveyData.status !== 'published') {
        message.warning("该问卷未发布");
        return;
      }
      setSurvey(surveyData);
      message.success("问卷加载成功");
    } catch (err) {
      message.error("加载失败：" + err.message);
    }
  };

  const handleSubmit = async (values) => {
    try {
      const email = getEmailFromToken();
      await submitSurveyAnswers(survey.id, email, Object.values(values));
      message.success("提交成功");

      form.resetFields();
      setSurvey(null);
      setFormValues({});
      setLocationInfo({});
      localStorage.removeItem('unsavedSurvey');
      localStorage.removeItem('unsavedSurveyValues');
    } catch (err) {
      message.error("提交失败：" + err.message);
    }
  };

  const scrollToQuestion = (index) => {
    questionRefs.current[index]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
  };

  const handleValuesChange = (changedValues, allValues) => {
    setFormValues(allValues);
  };

  const toggleNavigation = () => {
    setActiveNavigation(!activeNavigation);
  };

  // 处理获取位置
  const handleGetLocation = async (questionName) => {
    if (!navigator.geolocation) {
      message.error('您的浏览器不支持地理定位');
      return;
    }

    message.loading('正在获取位置信息...', 0);

    navigator.geolocation.getCurrentPosition(
      async (pos) => {
        const lat = pos.coords.latitude;
        const lng = pos.coords.longitude;
        const locationValue = `(${lat}, ${lng})`;
        
        // 设置表单值
        form.setFieldValue(questionName, locationValue);
        
        // 获取城市名
        const cityName = await getCityName(lat, lng);
        
        // 更新位置信息显示
        setLocationInfo(prev => ({
          ...prev,
          [questionName]: {
            latitude: lat.toFixed(6),
            longitude: lng.toFixed(6),
            city: cityName
          }
        }));
        
        message.destroy();
        message.success('位置获取成功');
      },
      (error) => {
        message.destroy();
        let errorMsg = '定位失败';
        switch (error.code) {
          case error.PERMISSION_DENIED:
            errorMsg = '用户拒绝了地理定位请求';
            break;
          case error.POSITION_UNAVAILABLE:
            errorMsg = '位置信息不可用';
            break;
          case error.TIMEOUT:
            errorMsg = '获取位置超时';
            break;
          default:
            errorMsg = '定位失败，请重试';
            break;
        }
        message.error(errorMsg);
      },
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 60000
      }
    );
  };

  const renderNavigationPanel = (questions) => {
    const questionsByType = questions.reduce((acc, q, index) => {
      if (!acc[q.type]) acc[q.type] = [];
      acc[q.type].push({ ...q, originalIndex: index });
      return acc;
    }, {});

    return (
      <div className="navigation-container">
        <div className="navigation-card">
          <div className="navigation-header" onClick={toggleNavigation}>
            <h4 className="navigation-title">题目导航</h4>
            {activeNavigation ? <UpOutlined /> : <DownOutlined />}
          </div>
          {activeNavigation && (
            <div className="navigation-content">
              {Object.entries(questionsByType).map(([type, qs]) => (
                <div key={type} style={{ marginBottom: 16 }}>
                  <h5>{typeLabels[type]}</h5>
                  <div className="question-indicators">
                    {qs.map((q) => {
                      const isAnswered = formValues[`q_${q.originalIndex}`] !== undefined &&
                        formValues[`q_${q.originalIndex}`] !== '';
                      return (
                        <div
                          key={`nav-${q.originalIndex}`}
                          onClick={() => scrollToQuestion(q.originalIndex)}
                          className={`question-indicator ${isAnswered ? 'answered' : 'unanswered'}`}
                        >
                          {q.originalIndex + 1}
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="writed-surveys-container">
      <Input.Search
        placeholder="粘贴问卷链接，例如：https://localhost:5173/surveys/xxxx"
        enterButton={<SearchOutlined />}
        value={surveyLink}
        onChange={(e) => setSurveyLink(e.target.value)}
        onSearch={handleLoadSurvey}
        className="survey-link-input"
      />

      {survey && (
        <>
          <Title level={4}>{survey.title}</Title>
          <p>{survey.description}</p>

          {(() => {
            const sortedQuestions = [...survey.questions].sort(
              (a, b) => typeOrder.indexOf(a.type) - typeOrder.indexOf(b.type)
            );

            return (
              <>
                {renderNavigationPanel(sortedQuestions)}

                <Form
                  form={form}
                  layout="vertical"
                  onFinish={handleSubmit}
                  onValuesChange={handleValuesChange}
                >
                  {sortedQuestions.map((q, idx) => {
                    const name = `q_${idx}`;
                    const rules = q.required ? [{ required: true, message: '必填' }] : [];
                    const labelPrefix = `${idx + 1}. ${typeLabels[q.type]}：`;

                    return (
                      <div
                        key={name}
                        ref={(el) => (questionRefs.current[idx] = el)}
                        className="question-item"
                      >
                        <Form.Item label={labelPrefix + q.title} name={name} rules={rules}>
                          {q.type === 'single' && (
                            <Radio.Group
                              options={q.options.map((o, i) => ({
                                label: getOptionLabelWithLetter(o, i),
                                value: o,
                              }))}
                              optionType="default"
                              style={{ display: 'flex', flexWrap: 'wrap', gap: '12px' }}
                            />
                          )}
                          {q.type === 'multiple' && (
                            <Checkbox.Group
                              options={q.options.map((o, i) => ({
                                label: getOptionLabelWithLetter(o, i),
                                value: o,
                              }))}
                              style={{ display: 'flex', flexWrap: 'wrap', gap: '12px' }}
                            />
                          )}
                          {q.type === 'text' && <Input.TextArea />}
                          {q.type === 'rating' && <Rate count={q.max || 5} />}
                          {q.type === 'location' && (
                            <div>
                              {/* 位置信息显示框 */}
                              {locationInfo[name] && (
                                <Card 
                                  size="small" 
                                  style={{ 
                                    marginBottom: 12, 
                                    backgroundColor: '#f6ffed',
                                    border: '1px solid #b7eb8f'
                                  }}
                                >
                                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                    <EnvironmentOutlined style={{ color: '#52c41a' }} />
                                    <div>
                                      <div style={{ fontWeight: 'bold', color: '#389e0d' }}>
                                        {locationInfo[name].city}
                                      </div>
                                      <div style={{ fontSize: '12px', color: '#666' }}>
                                        经度: {locationInfo[name].longitude}°, 
                                        纬度: {locationInfo[name].latitude}°
                                      </div>
                                    </div>
                                  </div>
                                </Card>
                              )}
                              
                              {/* 获取位置按钮 */}
                              <Button
                                icon={<EnvironmentOutlined />}
                                onClick={() => handleGetLocation(name)}
                              >
                                获取位置
                              </Button>
                            </div>
                          )}
                        </Form.Item>
                      </div>
                    );
                  })}

                  <Form.Item>
                    <Button type="primary" htmlType="submit">
                      提交问卷
                    </Button>
                  </Form.Item>
                </Form>
              </>
            );
          })()}
        </>
      )}
    </div>
  );
};

export default WritedSurveys;